<template>
    <div class="pool-list">
        <div class="move-box">
            <RiskLeftModule02
                v-model="inputValueLeft"
                @on-submit="submitInput"
                @on-handleNode="clickNode"
                :placeholders="ltitleName"
                :treeData="treeData"
                :leftHeight="leftHgt"
                :currentKey="'1'"
            >
                <template slot="ltitle">公司敞口信息</template>
            </RiskLeftModule02>

            <!-- 公司敞口信息 -->

            <RiskRightModule v-model="inputValueRight" :rightPlace="rtitleName" :rightHeight="leftHgt" @on-keyup="selectGroup">
                <p slot="rtitle">公司敞口信息</p>
                <span slot="button" class="dict-r-slot">
                    <el-button type="primary" size="mini" @click="selectGroup">查询</el-button>
                </span>
                <span slot="button" class="dict-r-slot" :style="{ display: cutInfo == '本地' ? '' : 'none' }">
                    <el-button type="primary" size="mini" v-authCode.show="B_0123" @click="addGroup">新增</el-button>
                </span>
                <span slot="button" class="dict-r-slot" :style="{ display: cutInfo == '本地' ? '' : 'none' }">
                    <el-button type="primary" size="mini" v-authCode.show="B_0147" @click="loadinGroup">导入</el-button>
                </span>
                <span slot="button" class="dict-r-slot">
                    <el-button type="primary" size="mini" v-authCode.show="B_0144" @click="downLoadGroupFile">导出</el-button>
                </span>
                <span slot="button" class="dict-r-slot" :style="{ display: cutInfo == '本地' ? '' : 'none' }">
                    <el-button type="danger" size="mini" v-authCode.show="B_0114" @click="deleteGroup">删除</el-button>
                </span>
                <slot>
                    <el-table :data="tableData" border size="mini" style="width: 100%" height="79vh" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" size="mini" align="center"> </el-table-column>
                        <el-table-column prop="type" label="公司敞口编号" min-width="120px" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="assetName" label="敞口名称" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="balance" label="敞口值" show-overflow-tooltip :formatter="formatterNumber" align="right">
                        </el-table-column>
                        <el-table-column prop="modifyUser" label="修改人" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="modifyDate" label="修改日期" show-overflow-tooltip align="center" sortable>
                            <template slot-scope="scope">
                                <span>{{dateFormat(scope.row.modifyDate)}} {{timeFormat(scope.row.modifyTime)}}</span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="modifyTime" label="修改时间" show-overflow-tooltip :formatter="formatterTime" align="center">
                        </el-table-column> -->
                        <el-table-column label="操作" width="120">
                            <template slot-scope="scope">
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-edit"
                                    v-authCode="B_0124"
                                    topTitle="修改"
                                    :disabled="cutInfo === '外部'"
                                    @on-click="editGroupRow(scope.row)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="danger"
                                    icon="el-icon-delete"
                                    v-authCode="B_0191"
                                    topTitle="删除"
                                    @on-click="deleteGroupRow(scope.row)"
                                    :disabled="cutInfo === '外部'"
                                    v-if="tableData.length > 0"
                                ></RiskIconButton>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block" v-show="tableData.length > 0">
                        <risk-pagination :paging="groupPage" @page-change="pageRet"></risk-pagination>
                    </div>
                </slot>
            </RiskRightModule>
        </div>
        <!-- 新增 -->
        <yh-dialog :title="groupDialog.title" :visible.sync="groupDialog.visible" width="435px" v-loading="loading" drag>
            <el-form label-width="140px" size="mini">
                <el-form-item label="公司敞口编号">
                    <el-input placeholder="自动生成" style="width: 220px" disabled v-model="groupData.type"></el-input>
                </el-form-item>
                <el-form-item label="敞口名称">
                    <el-input style="width: 220px" v-model="groupData.assetName" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="敞口值">
                    <el-input-number
                        v-model="groupData.balance"
                        style="width: 220px"
                        controls-position="right"
                        :min="0"
                        @change="handleInputBalance"
                    ></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="groupDialogClosed"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="groupDialogConfirm"> 确 定 </el-button>
            </div>
        </yh-dialog>
        <!-- 删除 -->
        <div>
            <yh-dialog drag :title="deleteDialog.title" :visible.sync="deleteDialog.visible" width="500px" v-loading="loading">
                <div class="remove-text">
                    <!-- <span v-for="(itme, index) in delPendingData" :key="index"> {{ itme }} , </span>? -->
                    <p>{{ delPendingData.join(' , ') }}</p>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="deleteDialogClosed"> 取 消 </el-button>
                    <el-button size="mini" type="primary" @click="deleteDialogConfirm">确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
        <!-- 导入明细 -->
        <div>
            <yh-dialog drag :title="loadinDialog.title" :visible.sync="loadinDialog.visible" width="650px" v-loading="loading">
                <div>
                    <el-button @click="putDictfile" type="primary" style="margin-bottom: 5px">选择文件</el-button><i> {{ fileNames }} </i>
                    <input type="file" ref="putInput" style="display: none" @change="putDictfiles" />
                    <el-table :data="putTableData" style="width: 100%" border size="mini" height="300px">
                        <el-table-column label="公司敞口编号" prop="type"></el-table-column>
                        <el-table-column label="敞口名称" prop="assetName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="敞口值" prop="balance"></el-table-column>
                    </el-table>
                    <el-pagination
                        background
                        @current-change="loadPageChange"
                        layout="total, prev, pager, next"
                        :total="loadPage.total"
                        :page-size="loadPage.pageSize"
                        :current-page.sync="loadPage.currentPage"
                        v-show="putTableData.length > 0"
                    ></el-pagination>
                    <span style="color: red">备注：导入格式请参考敞口导出的结果</span>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="loadinDialogClosed"> 取 消 </el-button>
                    <el-button size="mini" type="primary" @click="loadinDialogConfirm">确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';

import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTrantable from '@/common/components/risk-trantable.vue';
import { dateFormat, formatter, formatterDate, formatterNumber, formatterTime, getCurrentPageData, timeFormat } from '@/utils/tools';
import XEUtils from 'xe-utils';
import { DialogVO } from '@yhfin/biz';
import Dict from './dict/index';
import { downLoadFile } from '@/utils/request';
import * as XLSX from 'xlsx';
import RiskLeftModule02 from '@/common/components/risk-left-module02.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'CompanyInfo',
    components: {
        RiskLeftModule02,
        RiskRightModule,
        RiskIconButton,
        RiskTrantable,
        RiskPagination,
    },
})
export default class CompanyInfo extends Vue {
    formatterDate = formatterDate;
    formatterTime = formatterTime;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    formatter = formatter;
    formatterNumber = formatterNumber;
    private inputValueLeft: string = '';
    private ltitleName: string = '编号/名称';
    private leftHgt: string = '100vh';
    private inputValueRight: string = '';

    private rtitleName: string = '公司敞口编号/敞口名称';
    private localList: any[] = [];
    private outsideList: any[] = [];
    private groupDialog: DialogVO = new DialogVO();
    private deleteDialog: DialogVO = new DialogVO();
    private loadinDialog: DialogVO = new DialogVO();
    private putTableData: any[] = []; // 上传的数据
    private putTableDataList: any[] = []; // 上传的数据

    private fileNames: string = ''; // 上传文件名

    private groupDataBackup: any = {};
    private groupData: any = {
        type: '自动生成',
        assetName: '',
        balance: undefined,
    };

    private groupPage: pages = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };

    private loadPage: pages = {
        currentPage: 1,
        pageSize: 20,
        total: 0,
    };

    private treeData: any[] = [
        {
            id: '0',
            label: '本地',
            children: [],
        },
        {
            id: '1',
            label: '外部',
            children: [],
        },
    ];
    private cutInfo: string = '外部';
    private tableData: any[] = [];
    private tableDataList: any[] = [];
    private tableDataSearched: any[] = [];
    private hasSelectedData: any[] = [];
    private delPendingData: any[] = [];
    Dict: any = new Dict();

    mounted() {
        this.groupDataBackup = JSON.parse(JSON.stringify(this.groupData));
        this.getCompanyInfo();
    }

    // 分组分页切换
    pageRet() {
        if (this.inputValueRight) {
            this.groupPage.total = this.tableDataSearched.length;
            this.tableData = getCurrentPageData(this.tableDataSearched, this.groupPage.currentPage, this.groupPage.pageSize);
        } else {
            this.groupPage.total = this.tableDataList.length;
            this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
        }
    }

    // 分组分页切换
    // private groupPageChange(val: number): void {
    //     if (this.inputValueRight) {
    //         this.groupPage.total = this.tableDataSearched.length;
    //         this.groupPage.currentPage = val;
    //         this.tableData = getCurrentPageData(this.tableDataSearched, this.groupPage.currentPage, this.groupPage.pageSize);
    //     } else {
    //         this.groupPage.total = this.tableDataList.length;
    //         this.groupPage.currentPage = val;
    //         this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
    //     }
    // }

    private loadPageChange(val: number): void {
        this.loadPage.total = this.putTableDataList.length;
        this.loadPage.currentPage = val;
        this.putTableData = getCurrentPageData(this.putTableDataList, this.loadPage.currentPage, this.loadPage.pageSize);
    }

    // 公司敞口信息
    private getCompanyInfo(): void {
        this.$axios.get('/companyInfoSetting/companyAsset/byCondition').then((res: any) => {
            this.outsideList = res.filter(item => item.createType != '0');
            this.localList = res.filter(item => item.createType === '0');
            this.tableDataList = this.cutInfo === '本地' ? this.localList : this.outsideList;
            this.selectGroup();
        });
    }

    // 节点点击
    private clickNode(data: any): void {
        this.cutInfo = data.label;
        this.getGroupInfo();
    }

    // 获取公司敞口数据
    private getGroupInfo(): void {
        if (this.cutInfo === '本地') {
            this.tableDataList = this.localList;
        } else {
            this.tableDataList = this.outsideList;
        }
        this.selectGroup();
    }

    // 公司敞口查询
    private selectGroup(): void {
        this.tableDataSearched = this.handleFilter(this.tableDataList, this.inputValueRight, 'type', 'assetName');
        this.groupPage.currentPage = 1;
        this.pageRet();
    }

    // 公司敞口筛选数据
    private handleFilter(dataSource: any, param: any, code: string, name: string): any {
        if (!param || !dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item[name] || '')
                        .trim()
                        .toUpperCase()
                        .includes(param.trim().toUpperCase()) ||
                    (item[code] || '')
                        .trim()
                        .toUpperCase()
                        .includes(param.trim().toUpperCase())
            );
        }
    }

    // 公司敞口新增
    private addGroup(): void {
        this.groupData = JSON.parse(JSON.stringify(this.groupDataBackup));
        this.groupDialog = this.groupDialog.getAddDialog('新增公司敞口');
    }

    // 确认添加||修改公司敞口
    private groupDialogConfirm(): void {
        if (!this.groupData.assetName) {
            this.yh_message_error('敞口名称不能为空！');
            return;
        }

        if (!this.groupData.balance) {
            this.yh_message_error('敞口值不能为空！');
            return;
        }

        if (this.groupData.balance.toString().length > 10) {
            this.groupData.balance = parseInt(this.groupData.balance.toString().slice(0, 10));
            this.yh_message_warn('敞口值的最长长度为10');
            return;
        }

        if (this.groupDialog.action === 1) {
            this.$axios.post('/companyInfoSetting/add/company/asset', this.groupData).then(res => {
                this.yh_message_success('新增成功');
                this.getCompanyInfo();
                this.groupDialogClosed();
            });
        } else {
            this.$axios.put('/companyInfoSetting/update/companyAsset', this.groupData).then(res => {
                this.yh_message_success('编辑成功');
                this.getCompanyInfo();
                this.groupDialogClosed();
            });
        }
    }

    private groupDialogClosed(): void {
        this.groupDialog.visible = false;
    }

    // 公司敞口删除
    private deleteGroup(): void {
        if (this.hasSelectedData.length < 1) {
            this.yh_message_warn('未选择删除项');
        } else {
            this.delPendingData = this.hasSelectedData;
            this.deleteDialog = this.deleteDialog.getDeleteDialog('确定删除公司敞口？');
        }
    }

    // 确认删除
    private deleteDialogConfirm(): void {
        this.$axios({
            url: '/companyInfoSetting/delete/company/asset',
            method: 'post',
            data: this.delPendingData,
        }).then(res => {
            this.yh_message_success('删除成功');
            this.getCompanyInfo();
            this.deleteDialogClosed();
        });
        this.hasSelectedData = [];
    }

    private deleteDialogClosed(): void {
        this.deleteDialog.visible = false;
    }

    // 左侧搜索
    private submitInput(): void {}

    // 勾选
    private handleSelectionChange(data: any[]): void {
        this.hasSelectedData = XEUtils.map(data, item => item.type);
    }

    // 表格修改公司敞口
    private editGroupRow(row): void {
        this.groupDialog = this.groupDialog.getUpdateDialog('修改敞口');
        this.groupData = JSON.parse(JSON.stringify(row));
        //
        this.groupData.key = row.type;
        this.groupData.preType = row.type;
    }

    // 表格删除公司敞口
    private deleteGroupRow(row: any): void {
        this.delPendingData = [row.type];
        this.deleteDialog = this.deleteDialog.getDeleteDialog('确定删除公司敞口？');
    }

    // 公司敞口导出
    private downLoadGroupFile(): void {
        let type = this.cutInfo == '本地' ? '0' : '1';
        let data = this.hasSelectedData;
        if (!this.hasSelectedData || this.hasSelectedData.length < 1) {
            data = XEUtils.map(this.tableDataList, item => item.type);
        }
        if (data.length < 1) {
            this.yh_message_warn('导出列表为空,请添加数据在进行导出!');
            return;
        }
        downLoadFile({
            url: '/companyInfoSetting/outImport/' + type,
            method: 'post',
            data: data,
        });
    }

    // 导入
    private loadinGroup(): void {
        this.putTableData = [];
        this.fileNames = '';
        this.loadinDialog = this.loadinDialog.getAddDialog('导入公司敞口');
    }

    private putDictfile(): void {
        (this.$refs['putInput'] as any).click();
    }

    // 选取文件
    private putDictfiles(e) {
        let files = e.currentTarget.files;
        new Promise((resolve, reject) => {
            let reader = new FileReader();
            if (!files || files.length === 0) {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject();
            }
            reader.readAsBinaryString(files[0]);

            reader.onload = e => {
                let webBook = XLSX.read(e.target.result, { type: 'binary' });
                let data = [];
                for (let sheet in webBook.Sheets) {
                    if (webBook.Sheets.hasOwnProperty(sheet)) {
                        data = data.concat(XLSX.utils.sheet_to_json(webBook.Sheets[sheet]));
                        break;
                    }
                }
                resolve(data);
            };
            reader.onerror = error => {
                reject(error);
            };
        }).then((res: any) => {
            try {
                let entryDetails = [];
                entryDetails = res
                    .map(item => {
                        return { type: item.公司敞口编号, assetName: item.敞口名称, balance: item.敞口值, key: item.公司敞口编号 };
                    })
                    .filter(item => !!item.type);
                if (entryDetails.length === 0) {
                    (this.$refs['putInput'] as any).value = null;
                    this.putTableData = [];
                    this.fileNames = '';
                    this.yh_message_error('数据格式不正确或者数据为空，导入失败');
                    return;
                }
                let returnBole = this.returnDatsBol(entryDetails);
                if (returnBole) {
                    (this.$refs['putInput'] as any).value = null;
                    this.putTableData = [];
                    this.fileNames = '';
                    this.yh_message_error('敞口名称太长！导入失败');
                    return;
                }
                this.putTableDataList = entryDetails;
                this.loadPageChange(1);
                this.fileNames = files[0].name;
                (this.$refs['putInput'] as any).value = null;
            } catch (e) {
                this.putTableData = [];
                this.fileNames = '';
                (this.$refs['putInput'] as any).value = null;
                this.yh_message_error('数据格式不正确，导入失败');
            }
        });
    }

    returnDatsBol(val: any) {
        for (let i = 0; i < val.length; i++) {
            if (val[i].assetName.length > 50) {
                return true;
            }
            i++;
        }
    }

    private loadinDialogConfirm(): void {
        // 上传数据
        let entryDetails = this.putTableDataList;
        // 已存在的数据
        let fundInfoCache = this.tableDataList;
        let entryDetailsSet = new Set(entryDetails.map(item => item['type']));
        if (entryDetailsSet.size != entryDetails.length) {
            this.yh_message_warn('导入数据存在重复的编号!');
            return;
        }
        let repeatList = [];
        let repeatByfundCode = [];
        let importData = [];
        let balanceVerify = [];
        entryDetails.forEach(pItem => {
            if (!pItem.type || !pItem.assetName || !pItem.balance) {
                importData.push(pItem);
            }
            let dataImport = fundInfoCache.find(cItem => pItem.type === cItem.type);
            if (dataImport) {
                repeatList.push(dataImport);
            }
            if (Number(pItem.balance) <= 0) {
                balanceVerify.push(pItem);
            }
        });
        if (balanceVerify && balanceVerify.length) {
            this.yh_message_warn('敞口值不能为负数或零!');
            return;
        }
        if (importData && importData.length) {
            this.yh_message_warn('导入的数据有空值,请填写重新导入!');
            return;
        }
        if (!entryDetails || entryDetails.length === 0) {
            this.yh_message_warn('请选择需要上传的条目文件');
            return;
        }
        if (this.cutInfo === '本地') {
            this.$axios.post('/companyInfoSetting/add/company/assetImport', this.putTableDataList).then(res => {
                if (!res) {
                    this.yh_message_warn('导入公司资产失败,后端接口导入成功资产数量为:' + res);
                    return;
                }
                this.yh_message_success('导入成功');
                this.getCompanyInfo();
                this.loadinDialogClosed();
            });
        }
    }

    private loadinDialogClosed(): void {
        this.loadinDialog.visible = false;
    }

    private handleInputBalance(currentValue, oldValue) {
        if (currentValue && currentValue.toString().length > 10) {
            this.groupData.balance = parseInt(currentValue.toString().slice(0, 10));
            this.yh_message_warn('敞口值的最大长度为10位');
        } else {
            this.groupData.balance = currentValue;
        }
    }
}
</script>
<style lang="scss" scoped>
.pool-list {
    position: relative;
    height: 100%;
    .dict-r-slot {
        margin-right: 10px;
    }

    & /deep/ .el-dialog .el-dialog__body {
        max-height: 100vh;
    }
}
/deep/ .el-input-number__decrease:hover:not(.is-disabled) ~ .el-input .el-input__inner:not(.is-disabled),
/deep/ .el-input-number__increase:hover:not(.is-disabled) ~ .el-input .el-input__inner:not(.is-disabled) {
    border-color: #62b4f7;
}
/deep/ .el-table--border th:first-child .cell {
    padding-left: 6px;
}
</style>
